package hczc.longcai.com.hccrowdfunding.home.first_index.fragments;


import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;
import java.util.List;

import hczc.longcai.com.hccrowdfunding.R;
import hczc.longcai.com.hccrowdfunding.application.BaseApplication;
import hczc.longcai.com.hccrowdfunding.home.first_index.activities.Active_Details_Activity;
import hczc.longcai.com.hccrowdfunding.home.first_index.beans.Banner;
import hczc.longcai.com.hccrowdfunding.utils.bitmaputils.ImageLoader;


/**
 * 图片轮播Fragment
 * A simple {@link Fragment} subclass.
 */
public class SlideFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener, View.OnTouchListener {


    private static final String TAG = "SlideFragment";

    private View view;
    private ViewPager viewPager;
    private LinearLayout linearLayout;
    private List<ImageView> banners;
    private List<ImageView> barImages;
    private SlideAdapter adapter;

    private boolean flag = true;


    private int preposition = 0;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                update();

            }
        }
    };
    private List<Banner> banner;
    private SimpleDraweeView onlyOneBanner;
    private int size;
    private ImageLoader imageLoader;
    private View image;
    private ViewGroup container;

    public SlideFragment() {

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        banner = BaseApplication.dbIndexController.findBanners();
        size = banner.size();

        imageLoader = BaseApplication.imageLoader;

        Log.d(TAG, "******************" + size + "***************");

        if (size == 1) {

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_slide, container,false);
        BaseApplication.scaleScreenHelper.loadView(((ViewGroup) view));

        viewPager = ((ViewPager) view.findViewById(R.id.viewPager));
        onlyOneBanner = ((SimpleDraweeView) view.findViewById(R.id.banner));
        image = view.findViewById(R.id.banner_layout);

        int size = banner.size();
        if (size == 1) {
            viewPager.setVisibility(View.GONE);
            onlyOneBanner.setVisibility(View.VISIBLE);
            onlyOneBanner.setTag(banner.get(0).getPic());
            String pic = banner.get(0).getPic();
            onlyOneBanner.setImageURI(Uri.parse(pic));
        } else {

            initSlide();
        }
        return view;
    }


    private void initSlide() {
        linearLayout = ((LinearLayout) view.findViewById(R.id.linearLayout));
        initImages(1);
        initBar(1);
        barImages.get(0).setSelected(true);
        adapter = new SlideAdapter();
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(this);
//        viewPager.setOnTouchListener(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
//                    Log.d(TAG,"***********"+flag+"*************");
                    SystemClock.sleep(3000);
                    handler.sendEmptyMessage(0);
                }
            }
        }).start();

    }


    public void update() {
        int currentItem = viewPager.getCurrentItem();
        viewPager.setCurrentItem(++currentItem);
    }

    /**
     * 初始化轮播的图片
     *
     * @param length 图片的数量
     */
    private void initImages(int length) {
        banners = new ArrayList<>();
        ImageView imageView = null;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        for (int i = 0; i < length; i++) {
            imageView = new ImageView(getActivity());
            imageView.setImageResource(R.mipmap.banner);
            imageView.setLayoutParams(params);
//            imageView.setOnTouchListener(this);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setOnClickListener(this);
            banners.add(imageView);
        }
    }

    /**
     * 初始化图片下面的指示条
     *
     * @param length
     * @return
     */
    private List<ImageView> initBar(int length) {
        barImages = new ArrayList<>();
        ImageView imageView = null;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(5, 0, 5, 0);
        for (int i = 0; i < length; i++) {
            imageView = new ImageView(getActivity());
            imageView.setImageDrawable(getResources().getDrawable(R.drawable.slide));
            imageView.setLayoutParams(params);
            barImages.add(imageView);
            linearLayout.addView(imageView);
        }
        return barImages;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

//        Log.d(TAG,"*****"+position+"*****"+positionOffset+"*****"+positionOffsetPixels);
    }

    @Override
    public void onPageSelected(int position) {
        barImages.get(position % barImages.size()).setSelected(true);
        barImages.get(preposition).setSelected(false);
        preposition = position % barImages.size();
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Override
    public void onClick(View view) {
//        Toast.makeText(getActivity(),"点击了图片",Toast.LENGTH_SHORT).show();
        startActivity(new Intent(getActivity(), Active_Details_Activity.class));
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
//        switch (event.getAction()) {
//            case MotionEvent.ACTION_DOWN:
//                flag = false;
//                break;
//            case MotionEvent.ACTION_SCROLL:
//                flag = false;
//                break;
//            case MotionEvent.ACTION_CANCEL:
//                flag = true;
//                break;
//            case MotionEvent.ACTION_MOVE:
//
//        }
//
        return false;
    }


//    @Override
//    public void response(Bitmap bitmap, String url) {
//        banners.get(0).setImageBitmap(bitmap);
//    }


    class SlideAdapter extends PagerAdapter {


        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if (banners.get(position % banners.size()).getParent() != null) {
                container.removeView(banners.get(position % banners.size()));
            }
            container.addView(banners.get(position % banners.size()));
            return banners.get(position % banners.size());
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            Log.d(TAG,position+"");
//            container.removeView(banners.get(position % banners.size()));
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        flag = false;
        super.onDestroy();
    }


}
